package com.atguli.server.Util;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Security;


/**
 * @author DPF
 */
public class CryptUtil {
    static {
        Provider provider = Security.getProvider("BC");
        if (provider == null) {
            Security.addProvider(new BouncyCastleProvider());
        }
    }

    public static String cryptSm3(String salt, String pwd) {
        try {
            MessageDigest sm3 = MessageDigest.getInstance("SM3","BC");
            byte[] data = (salt + pwd).getBytes(StandardCharsets.UTF_8);
            byte[] hashValue = sm3.digest(data);
            return bytesToHex(hashValue);
        } catch (Exception e) {
            throw new RuntimeException("加密失败", e);
        }
    }

    public static String cryptSha1(String salt, String pwd) {
        try {
            MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
            byte[] data = (salt + pwd).getBytes(StandardCharsets.UTF_8);
            byte[] hashValue = sha1.digest(data);
            return bytesToHex(hashValue);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("加密失败", e);
        }
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xFF & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

}
